<template>
  <div class="content-box">
    <div class="ceshibox">
      <el-button
        type="primary"
        @click="dialogFormVisible = true"
        class="addBtn"
        icon="el-icon-plus"
        >添加材料</el-button>
      
      <vxe-table
        resizable
        show-overflow
        ref="xTree"
        keep-source
        @cell-click="cellClickEvent"
        @edit-closed="kkk"
        :tree-config="{
          children: 'children',
          showIcon: true,
          expandAll: true,
          transform: true,
        }"
        highlight-current-row
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
          activeMethod: activeCellMethod,
        }"
        :data="tableData"
      >
        <vxe-table-column type="seq" width="100"></vxe-table-column>
        <vxe-table-column field="modules__name" title="类目" tree-node>
        </vxe-table-column>
        <vxe-table-column field="modules__unit" title="单位">
        </vxe-table-column>
        <vxe-table-column field="materials_num" title="数量">
        </vxe-table-column>
        <vxe-table-column field="materials_price" title="价格">
        </vxe-table-column>
        <vxe-table-column field="create_time" title="最后添加时间" width="25%">
          <!-- width="200px" -->
          <template v-slot="{ row }">
            {{
              row.create_time.split("T")[0] +
              " - " +
              row.create_time.split("T")[1].split(".")[0]
            }}
          </template>
        </vxe-table-column>
        <!-- <vxe-table-column
          v-for="(item, index) in placeList"
          :title="item.name"
          :field="'maindata[' + index + '].money'"
          :edit-render="{ name: 'input' }"
          :key="item.id"
        >
        </vxe-table-column> -->
        <!-- <vxe-table-column
          field="title"
          title="备注"
          width="200"
          :edit-render="{ name: 'input' }"
        ></vxe-table-column> -->
      </vxe-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加对话框 -->
    <el-dialog
      title="添加材料"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :before-close="closeAndResetaddFrom"
    >
      <el-form :model="addForm" ref="addFormRef" :rules="addFromrules">
        <el-form-item label="选择材料" label-width="115px" prop="modules_id">
          <el-cascader
            ref="Mycascader"
            v-model="addValue"
            :options="options"
            :props="optionsProps"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="材料数量" label-width="115px" prop="materials_num">
          <el-input
            v-model="addForm.materials_num"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="材料价格"
          label-width="115px"
          prop="materials_price"
        >
          <el-input
            v-model="addForm.materials_price"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAndResetaddFrom">取 消</el-button>
        <el-button type="primary" @click="addmaterials">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { UpdateArticalData } from "@/api/article";
import { postmaterials, getAllmaterials } from "@/api/store";
import { getpermissionsMaterialss } from "@/api/project";
export default {
  data() {
    return {
      tableData: [],
      // 项目ID 和用户ID
      project_id: "",
      people_id: "",
      page: 1,
      page_size: 10,
      total: 0,
      placeList: [],
      upData: [],
      rowData: [],
      // 级联选择器对应数据
      addValue: [],
      options: [],
      optionsProps: {
        value: "id",
        label: "name",
        key: "pid",
      },
      // 添加表单
      addForm: {
        project_id: this.$route.query.id,
        modules_id: "",
        materials_num: "",
        materials_price: "",
      },
      dialogFormVisible: false,
      // 添加表单非空验证
      addFromrules: {
        modules_id: [
          { required: true, message: "请选择而材料名称", trigger: "blur" },
        ],
        materials_num: [
          { required: true, message: "请输入材料数量", trigger: "blur" },
        ],
        materials_price: [
          { required: true, message: "请输入材料金额", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.project_id = this.$route.query.id;
    this.people_id = localStorage.getItem("id");
  },
  mounted() {
    this.getDeparts();
    this.getmaterials();
  },

  methods: {
    // 根距权限获取所有以添加的材料
    async getmaterials() {
      const res = await getAllmaterials({
        project_id: this.project_id,
        people_id: this.people_id,
        page: this.page,
        page_size: this.page_size,
      });
      console.log("已经添加的材料", res);
      if (res.code == 200) {
        this.total = res.data.total;
        this.tableData = res.data.data;
      }
    },
    // 分页数据改变触发事件
    handleSizeChange(val) {
      this.page_size = val;
      this.getmaterials();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getmaterials();
    },
    // 获取所有可以添加的材料信息
    async getDeparts() {
      var dayTimes =
        new Date().getFullYear() +
        "-" +
        new Date().getMonth() +
        "-" +
        new Date().getDate();
      let tableList = [];
      // getRoutes
      const res = await getpermissionsMaterialss({
        project_id: this.project_id,
        people_id: this.people_id,
        // start_day: dayTimes,
        // end_day: dayTimes,
      });

      console.log(res);
      if (res.code == 200) {
        this.options = res.data;
      }
      // if (res.code === 200) {
      //   res.moduleslist.forEach((item) => {
      //     console.log(item.is_materials);
      //     if (item.is_materials == true) {
      //       tableList.push(item);
      //     }
      //   });
      //   this.tableData = tableList;
      //   this.placeList = res.placelist;

      //   this.$nextTick(() => this.$refs.xTree.setAllTreeExpand(true));
      // }
      // console.log(this.tableData, "sdada", this.placeList, "dsadasd");
    },
    // 级联选择器发生变化触发
    handleChange(value) {
      let lastId = this.addValue[this.addValue.length - 1];
      this.addForm.modules_id = lastId;
    },
    // 关闭并重置添加表单
    closeAndResetaddFrom() {
      this.dialogFormVisible = false;
      this.addValue = [];
      this.addForm.modules_id = "";
      this.$refs.addFormRef.resetFields();
    },
    // 添加材料
    async addmaterials() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          postmaterials(this.addForm)
            .then((res) => {
              this.$message.success("材料添加成功");
              this.closeAndResetaddFrom();
              this.getDeparts();
              this.getmaterials();
            })
            .catch((err) => {
              this.$message.error("测算总金额和测算总工程量只能是数值");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //单元格失去焦点时修改
    async kkk(row, rowIndex) {
      const arr = this.rowData;
      let list = row.row.maindata;
      var objNum = {};
      var isExist = false;
      for (var i = 0; i < list.length; i++) {
        var obj = list[i];
        var money = obj.money;
        // var isExist = false;
        for (var j = 0; j < this.upData.length; j++) {
          if (this.upData[i].money != money) {
            const res = await UpdateArticalData(obj);
            if (res.code === 200) {
              isExist = true;
              this.getDeparts();
            }
          }
        }
      }
      if (isExist) {
        return this.$message.success("修改成功");
      }
    },

    //点击单元格触发@cell-click="cellDown"
    cellClickEvent(row) {
      this.rowData = row.row.maindata;
      this.upData = row.row.maindata;
    },

    //禁止编辑
    activeCellMethod({ row, rowIndex }) {
      this.upData = [];
      row.maindata.forEach((res) => {
        this.upData.push({ ...res });
      });
      if (row.children !== undefined) {
        this.$XModal.message({
          message: "禁止编辑",
          status: "error",
        });
        return false;
      }
      return true;
    },

    
  },
};
</script>

<style lang="scss" scoped>
.content-box {
  padding: 20px 0;
  width: 100%;
  .addBtn {
    margin-bottom: 12px;
  }
  .content-table {
    width: 96%;
    margin: 0 auto;
    margin-bottom: 1.25rem;
  }

  .head-row {
    margin-top: 1.25rem;
    margin-left: 1.75rem;
    margin-bottom: 1.25rem;

    .el-col {
      margin-left: 1.75rem;
    }
  }

  .vxebtn {
    margin-left: 0.625rem;
    text-align: center;
  }

  .ceshibox {
    width: 70%;
    margin: 2rem auto 0;
    // margin-top: 2rem;
    // margin-left: 2.25rem;
    // margin-right: 2.25rem;
    .btn {
      margin-bottom: 10px;
    }
  }
  .el-pagination {
    margin: 20px 0;
    float: right;
  }
}
</style>